package com.wf.controller;

import com.alibaba.fastjson.JSONObject;
import com.wf.dto.InvoiceDTO;
import com.wf.service.ContractInfoService;
import com.wf.service.InvoiceService;
import com.wf.utils.RedisUtil;
import com.wf.vo.Result;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import nuonuo.open.sdk.NNOpenSDK;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;

import java.util.HashMap;
import java.util.Iterator;
import java.util.Set;
import java.util.UUID;

/**
 * @Author: zhiyu
 * @Date:11:09
 * @DESC:
 */
@RestController
@Api("发票申请控制层")
@CrossOrigin
public class InvoiceController {
    @Autowired
    InvoiceService invoiceService;
    @Autowired
    RedisUtil redisUtil;
    @Autowired
    ContractInfoService contractInfoService;
    @ApiOperation("发票申请方法")
    @PostMapping("/billing")
    public Result billing(@RequestBody InvoiceDTO invoiceDTO) {
        HashMap<String,Object> map = JSONObject.parseObject(JSONObject.toJSONString(invoiceDTO),HashMap.class);
        String json = NNOpenSDK.getIntance().getMerchantToken("SD63236305","SDDED2523BED4643");
        JSONObject newresult = JSONObject.parseObject(json);
        String token = newresult.getString("access_token");
        String senid = UUID.randomUUID().toString().replace("-", ""); // 唯一标识，32位随机码，无需修改，保持默认即可
        String submit = invoiceService.submitInvoice(invoiceDTO, token, senid);
        String result = invoiceService.getResult(submit, token, senid);
        System.out.println("result = " + result);
        if (result.contains("获取成功")){
            Set<HashMap<String, Object>> hashMaps = contractInfoService.selectInvoiceRequest();
            Iterator<HashMap<String, Object>> iterator = hashMaps.iterator();
            while (iterator.hasNext()){
                HashMap<String, Object> next = iterator.next();
                String s1 = (String) next.get("trade_no");
                String s2 = (String) map.get("trade_no");
                if (s1.equals(s2)){
                    long l = redisUtil.setRemove("apartment::invoice::apply", next);
                    System.out.println("l = " + l);
                }
            }
            return Result.success(true);
        }else {
            return Result.success(false);
        }
    }
}
